package com.xu.InterruptedExeception;

/**
 * 当阻塞方法收到中断请求的时候就会抛出InterruptedException异常
 * @author xudenghui
 * @create 2023-02-24 15:01
 **/
public class InterruptedExceptionTest {

    public static void main(String[] args) throws InterruptedException {

        test1();
//        test2();
//        test3();
    }

    // 主线程执行   子线程任务抛出异常 仍然不会停止执行打印
    private static void test1() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Hello,World");
            }
        }, "print-thread");
        thread.start();
        thread.interrupt();
    }


    // 当线程状态是未中断时才执行打印
    private static void test2() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (!Thread.interrupted()) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Hello,World");
            }
        }, "print-thread");
        thread.start();
        Thread.sleep(2000);
        thread.interrupt();
    }


    private static void test3() throws InterruptedException {
        Thread thread = new Thread(() -> {
            // 当线程状态是未中断时才执行打印
            while (!Thread.interrupted()) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // 将中断状态置位true
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }
                System.out.println("Hello,World");
            }
        }, "print-thread");
        thread.start();
        Thread.sleep(2000);
        thread.interrupt();

    }


}
